import Input from '@/components/Input';
import NavBar from '@/components/Navbar';
import Textarea from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  UpdatephtotAction,
  UpdateprofileAction,
  userprofileAction,
} from '@/store/action/user';
import { ProfileType } from '@/store/reducer/user';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import dayjs from 'dayjs';
import { cleartoken } from '@/utils/storage';
import { useHistory } from 'react-router-dom';
// 2. 定义editType的类型
type EditType = 'photo' | 'gender' | 'name' | 'intro';
export default function ProfileEdit() {
  const history = useHistory();
  const dispatch = useDispatch();
  // 生命周期
  useEffect(() => {
    dispatch(userprofileAction());
  }, [dispatch]);
  //  定义state.editType,显示对应弹出框内容
  const [editType, setEditType] = useState('' as EditType);
  //  获取数据，渲染界面
  const { profile } = useAppSelector((state) => state.user);
  // 底部弹出层显示状态
  const [popupBottom, setPopupBottom] = useState(false);
  /**  右侧弹出层是否显示 */
  const [rightVisible, setRightVisible] = useState(false);
  // 声明state控制name
  const [name, setName] = useState('');
  //  声明状态，收集简介
  const [intro, setIntro] = useState('');
  //  声明state控制日期选择是否显示
  const [birthVisible, setBirthVisible] = useState(false);
  // 修复默认值, 使用useEffect监听name
  useEffect(() => {
    setName(profile.name || '');
  }, [profile.name]);
  // 4. 同步初始值
  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);
  //  创建ref，保存上传按钮
  const uploadRef = useRef<HTMLInputElement>(null);
  const handleUpload = () => {
    // {/*  onClick事件，触发上传按钮的click事件 */}
    uploadRef.current?.click();
  };
  // 更新照片
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    // 判断有无照片
    if (e.target.files) {
      console.log('e.target.files[0]  ----->  ', e.target.files[0]);
      // 声明formData，转换数据类型
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      // 调用更新头像action
      dispatch(UpdatephtotAction(formData));
      // 4.提示用户
      Toast.show({ content: '更新成功' });
      // 关闭弹出框
      setPopupBottom(false);
    }
  };
  /** 打开底部编辑的弹出层 */
  const handleShowEdit = (editType: EditType) => {
    // 改变弹出框内容
    setEditType(editType);
    // 关闭弹出框
    setPopupBottom(true);
  };
  /** 打开右侧编辑的弹出层 */
  const handleShowRightEdit = (editType: EditType) => {
    // 同时修改editType和rightVisible的值
    setEditType(editType);
    setRightVisible(true);
  };
  // 编辑性别,昵称复用
  const handleUploadprofile = async (data: Partial<ProfileType>) => {
    await dispatch(UpdateprofileAction(data));
    // 提示用户
    Toast.show({ content: '更新成功' });
    // 关闭弹出框
    setPopupBottom(false);
    setRightVisible(false);
    setBirthVisible(false);
  };
  /** 1. 定义方法 handleBack */
  const handleBack = () => {
    setRightVisible(false);
    editType === 'name' && setName(profile.name);
    editType === 'intro' && setIntro(profile.intro);
  };

  // 2. 监听input的keyDown事件，回车时更新
  const handleKeyDown = (
    e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    if (e.key === 'Enter') {
      editType === 'name' && handleUploadprofile({ name });
      editType === 'intro' && handleUploadprofile({ intro });
    }
  };
  const handleLogOut = () => {
    // 2 二次确认
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定退出吗？',
      onConfirm: () => {
        /* 3. 清除token */
        cleartoken();
        /* 4. 跳转页面 */
        history.push('/login');
        /* 5. 提示用户 */
        Toast.show({ content: '退出成功' });
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>
        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleShowEdit('photo')}
            >
              头像
            </List.Item>

            {/* 3. 点击时显示右侧弹出层  */}
            <List.Item
              arrow
              extra={profile.name}
              onClick={() => handleShowRightEdit('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handleShowRightEdit('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handleShowEdit('gender')}
            >
              性别
            </List.Item>
            {/* 3. 点击时显示日期选择 */}
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            // 2. ref绑定上传按钮
            ref={uploadRef}
            className="avatar-upload"
            type="file"
            onChange={(e) => handleFileChange(e)}
          />
        </div>
        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogOut}>
            退出登录
          </button>
        </div>
        <Popup
          visible={popupBottom}
          position="bottom"
          bodyClassName="popup-bottom-list"
          onMaskClick={() => setPopupBottom(false)}
        >
          {/* 3. 根据type做条件渲染 */}
          {editType === 'photo' && (
            <>
              <div className="list-item" onClick={handleUpload}>
                拍照
              </div>
              <div className="list-item" onClick={handleUpload}>
                本地选择
              </div>
              <div className="list-item" onClick={() => setPopupBottom(false)}>
                取消
              </div>
            </>
          )}
          {editType === 'gender' && (
            <>
              <div
                className="list-item"
                onClick={() => handleUploadprofile({ gender: 0 })}
              >
                男
              </div>
              <div
                className="list-item"
                onClick={() => handleUploadprofile({ gender: 1 })}
              >
                女
              </div>
              <div className="list-item" onClick={() => setPopupBottom(false)}>
                取消
              </div>
            </>
          )}
        </Popup>
        {/* 右侧弹出层 */}
        <Popup
          visible={rightVisible}
          position="right"
          bodyClassName="popup-right"
          destroyOnClose
        >
          {editType === 'name' && (
            <>
              <NavBar
                onBack={handleBack}
                right={
                  <span
                    className="submit-btn"
                    onClick={() => handleUploadprofile({ name })}
                  >
                    提交
                  </span>
                }
              >
                编辑用户信息
              </NavBar>
              <div className="edit-content">
                <h3 className="edit-title">编辑昵称</h3>
                <Input
                  className="edit-input"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  autoFocus
                  onKeyDown={(e) => handleKeyDown(e)}
                />
              </div>
            </>
          )}
          {editType === 'intro' && (
            <>
              <NavBar
                onBack={handleBack}
                right={
                  // 3 点击提交
                  <span
                    className="submit-btn"
                    onClick={() => handleUploadprofile({ intro })}
                  >
                    提交
                  </span>
                }
              >
                编辑简介
              </NavBar>
              <Textarea
                onKeyDown={(e) => handleKeyDown(e)}
                value={intro}
                // 2. onChange收集数据
                onChange={(e) => setIntro(e.target.value)}
              ></Textarea>
            </>
          )}
        </Popup>
        <DatePicker
          title="选择生日"
          // 2. 控制visible
          visible={birthVisible}
          // 4 设置最大最小值
          max={new Date()}
          min={new Date('1900-01-01')}
          // 5. 控制默认值
          defaultValue={new Date()}
          value={new Date(profile.birthday)}
          // 6. 选中生日
          onConfirm={(val) =>
            handleUploadprofile({ birthday: dayjs(val).format('YYYY-MM-DD') })
          }
          // 7. 取消
          onClose={() => setBirthVisible(false)}
        ></DatePicker>
      </div>
    </div>
  );
}
